package webshop.del;

import java.io.IOException;
import java.io.PrintWriter;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import webshop.data.del.Department;
import webshop.data.del.Employee;




/**
 * EmployeeDeleteServlet deletes an employee.
 * @author even
 */
public class EmployeeDeleteServlet  extends AbstractDepartmentServlet {
    @Resource
    UserTransaction tx;

    
    /**
     * Handle requests. Sends a html page containing the department list.
     *
     * @param req the request object
     * @param resp the response object
     *
     * @throws IOException
     * @throws ServletException
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        EntityManager em = emf.createEntityManager();
        PrintWriter out = response.getWriter();
        
        Employee emp = null;
        Exception reason = null;
        boolean deleted = false;
        
        try { // try to remove the employee
            tx.begin();
            String tmp = request.getParameter("empno");
            long empNo = Long.valueOf(tmp);
            emp = em.find(Employee.class, empNo);
            if (emp != null) {
                Department d = emp.getDepartment();
                if ( d!= null) d.removeEmployee(emp);
                em.remove(emp);
                tx.commit();
                deleted = true;
            }
        }
        catch (Exception e) {
            reason = e;
        }

        response.setContentType("text/html");
        response.setHeader("Cache-control", "no-cache");
        response.setHeader("Expires", "0");

        out.println("<html><head><title>"+this.getClass().getName()+"</title></head><body>");
        out.println("<h1>Delete Employee</h1>");
           
        if (deleted) {
            out.println("<p>Employee "+emp+" successfully deleted!</p>");
        }
        else {
            out.println("<p>Deleting Employee "+emp+" failed!");
            if (reason != null) {
                out.println("Reason:</p>");
                out.println("<pre>");
                reason.printStackTrace(out);
                out.println("</pre>");
            }
        }

        out.println("<hr/>");
        out.print("<p><a href=\"index.html\">Home</a>");
        out.println(" &gt; <a href=\"deplist\">Department List</a>");
        out.println("</body>");
        out.println("</html>");
    }

}
